package com.bsh.utils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.google.gson.Gson;

/**
 * 简单缓存
 * 
 * @author gsh
 *
 * @param <T>
 */
public class SimpleCache<T> {
	private final Integer m_lExpireTime;
	Gson gson = new Gson();

	RedisUtil ru = null;

//	RedisSentinelUtils ru = null;
	
	public SimpleCache() {
		this(500);
	}

	public SimpleCache(final int nExpireTime) {
		m_lExpireTime = nExpireTime;
		ru = RedisUtil.getRu();
		//ru =RedisSentinelUtils.getRu();
	}

	public long GetExpireTime() {
		return m_lExpireTime;
	}

	public void Put(final String name, final T obj) {
		ru.setex(name, gson.toJson(obj), m_lExpireTime);
	}

	public void Put(final String name, final T obj, final int expireTime) {
		ru.setex(name, gson.toJson(obj), expireTime);
	}

	public T Get(final String name, Class<T> type) {
		String json = ru.get(name);
		if (org.apache.commons.lang3.StringUtils.isEmpty(json))
			return null;
		return gson.fromJson(json, type);
	}

	public T Get(final String name) {
		String json = ru.get(name);
		if (org.apache.commons.lang3.StringUtils.isEmpty(json))
			return null;
		Class<T> type = getTClass();
		return gson.fromJson(json, type);
	}

	public boolean exists(String key) {
		return ru.exists(key);
	}

	public Class<T> getTClass() {
		Class<T> entityClass = null;
		Type t = getClass().getGenericSuperclass();
		if (t instanceof ParameterizedType) {
			Type[] p = ((ParameterizedType) t).getActualTypeArguments();
			entityClass = (Class<T>) p[0];
		}
		return entityClass;
	}
}
